package com.spzx.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.user.service.ISmsService;
import com.spzx.user.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author GQS @Date 2024/10/13/11:35 @Description
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void send(String phone) {

        // 将验证码存入redis
        String code = new DecimalFormat("0000").format(new Random().nextInt(10000));
        redisTemplate.opsForValue().set("phone:code:"+phone , code, 5, TimeUnit.MINUTES);

        // 发送验证码
        sendCode(phone,code);

    }

    private void sendCode(String phone, String code) {
        String host = "https://zwp.market.alicloudapi.com";
        String path = "/sms/sendv2";
        String method = "GET";
        String appcode = "6e125298cf0e49a3805302957b2fef4f";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("content", "【智能云】您的验证码是"+code+"。如非本人操作，请忽略本短信");

            try {
                HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
                System.out.println(response.toString());
                //获取response的body
                //System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (Exception e) {
                e.printStackTrace();
            }

    }
}
